import config from "@/config/index.js";
let { mainColor } = config
// import { Base64 } from 'js-base64';

export default {
  //discount显示函数
  displayDiscountPercent(p) {
    let rem = Math.floor(p / 100)
    if (rem >= 10) {
      return (rem % 10 == 0) ? (rem / 10) : rem
    } else {
      return '0.' + rem
    }
  },

  // 保留小数点后两位
  cutOutNum(t) {
    return t.toString().match(/^\d*(\.?\d{0,2})/g)[0] || null
  },

  // 获取斜杠后面的内容
  substringFn(t) {
    var htmlHref = t
    htmlHref = htmlHref.replace(/^http:\/\/[^/]+/, '')
    var addr = htmlHref.substr(
      htmlHref.lastIndexOf('/', htmlHref.lastIndexOf('/') - 1) + 1
    )
    var index = addr.lastIndexOf('/')
    //js 获取字符串中最后一个斜杠后面的内容
    var addrLast = decodeURI(addr.substring(index + 1, addr.length))
    return addrLast
  },

  // 时间格式化
  dateTimeFormateFn(date, type) {
    if (!date) {
      return
    } else {
      var d = new Date(date);
      d = d.getFullYear() > 0 ? d : new Date(Date.parse(date.replace(/-/g, "/")));        //为了兼容ios
      var year = d.getFullYear();
      var month = ('0' + (d.getMonth() + 1)).slice(-2);
      var day = ('0' + (d.getDate())).slice(-2);
      var hour = ('0' + (d.getHours())).slice(-2);
      var minutes = ('0' + (d.getMinutes())).slice(-2);
      var seconds = ('0' + (d.getSeconds())).slice(-2);
      switch (type) {
        case 'all':
          return `${year}-${month}-${day} ${hour}:${minutes}:${seconds}`
        case 'dayMinutes':
          return `${month}.${day} ${hour}:${minutes}`;
        case 'time':
          return `${hour}:${minutes}:${seconds}`
        case 'month':
          return Number(month)
        case 'year':
          return year
        case 'monthDate':
          return `${month}-${day}`;
        case 'yearMonth':
          return `${year}-${month}`;
        case 'day':
          return day;
        default:
          return `${year}-${month}-${day}`;
      }
    }
  },

  // 取随机数
  randomNum(maxNum, minNum, decimalNum) {
    // 获取指定范围内的随机数, decimalNum指小数保留多少位
    var max = 0,
      min = 0;
    minNum <= maxNum ? (min = minNum, max = maxNum) : (min = maxNum, max = minNum);
    switch (arguments.length) {
      case 1:
        return Math.floor(Math.random() * (max + 1));
      case 2:
        return Math.floor(Math.random() * (max - min + 1) + min);
      case 3:
        return (Math.random() * (max - min) + min).toFixed(decimalNum);
      default:
        return Math.random();
    }
  },

  //获取页面中某元素的绝对坐标位置
  // 获取顶部div的距离
  getParentTop(e) {
    var offset = e.offsetTop
    if (e.offsetParent != null) {
      offset += this.getParentTop(e.offsetParent)
    }
    return offset
  },

  // 获取左侧div的距离
  getParentLeft(e) {
    var offset = e.offsetLeft
    if (e.offsetParent != null) {
      offset += this.getParentLeft(e.offsetParent)
    }
    return offset
  },

  //打乱数组顺序
  shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
      // Pick a random index
      let index = Math.floor(Math.random() * counter);

      // Decrease counter by 1
      counter--;

      // And swap the last element with it
      let temp = array[counter];
      array[counter] = array[index];
      array[index] = temp;
    }

    return array;
  },

  // Build a URL with query arguments
  buildUrl(base, queries) {
    let ret = base
    if (typeof (queries) == 'undefined') return ret
    let isFirst = true
    for (let key in queries) {
      let value = queries[key]
      if (isFirst) {
        ret += '?'
        isFirst = false
      } else {
        ret += '&'
      }
      if (typeof (value) == 'undefined' || value === null) {
        ret += key
      } else {
        //ret += key + '=' + encodeURIComponent(value)
        ret += key + '=' + value
      }
    }
    return ret
  },

  // 将数字取整为10的倍数
  //   @param {Number} num 需要取整的值
  //  * @param {Boolean} ceil 是否向上取整
  //  * @param {Number} prec 需要用0占位的数量
  formatInt(num, prec = 2, ceil = false) {
    const len = String(num).length;
    if (len <= prec) { return num };

    const mult = Math.pow(10, prec);
    return ceil ?
      Math.ceil(num / mult) * mult :
      Math.floor(num / mult) * mult;
  },

  //获取时分秒
  parseTime(ms) {
    return {
      days: Math.floor(ms / 86400000),
      hours: Math.floor((ms % 86400000) / 3600000),
      minutes: Math.floor((ms % 3600000) / 60000),
      seconds: Math.floor((ms % 60000) / 1000),
      milliseconds: ms % 1000,
    }
  },


  // 判断Json是否为空
  isEmptyObject(data) {
    let arr = Object.keys(data);
    return arr.length == 0
  },

  //判断是不是微信打开
  isWeiXin() {
    const ua = window.navigator.userAgent
    return ua.match(/MicroMessenger/i) == 'MicroMessenger'
  },

  //判断H5页面是否在企业微信环境中打开
  isWxWork() {
    var ua = navigator.userAgent.toLowerCase(); // 将用户代理头的值转为小写
    return ua.match(/wxwork/i) == 'wxwork'
  },

  //对象里面的值都清空
  objValueIsEmpty(form) {
    for (let key in form) {
      form[key] = ''
    }
    return form
  },

  //将阿拉伯数字翻译成中文的大写数字
  numberToChinese(num) {
    var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十");
    var BB = new Array("", "十", "百", "仟", "萬", "億", "点", "");
    var a = ("" + num).replace(/(^0*)/g, "").split("."),
      k = 0,
      re = "";
    for (var i = a[0].length - 1; i >= 0; i--) {
      switch (k) {
        case 0:
          re = BB[7] + re;
          break;
        case 4:
          if (!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$")
            .test(a[0]))
            re = BB[4] + re;
          break;
        case 8:
          re = BB[5] + re;
          BB[7] = BB[5];
          k = 0;
          break;
      }
      if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0)
        re = AA[0] + re;
      if (a[0].charAt(i) != 0)
        re = AA[a[0].charAt(i)] + BB[k % 4] + re;
      k++;
    }

    if (a.length > 1) // 加上小数部分(如果有小数部分)
    {
      re += BB[6];
      for (var i = 0; i < a[1].length; i++)
        re += AA[a[1].charAt(i)];
    }
    if (re == '一十')
      re = "十";
    if (re.match(/^一/) && re.length == 3)
      re = re.replace("一", "");
    return re;
  },

  //多维数组得深拷贝
  deepcopy(obj) {
    return JSON.parse(JSON.stringify(obj))
  },

  //对象转成数组
  objTurnArr(obj) {
    return Object.entries(obj).map(([key, value]) => ({
      label: key,
      value: value
    }));
  },

  //第一个对象取值 给第二个对象赋值
  formatFunction(param1, param2) {
    Object.keys(param2).forEach(function(v) {
      if (param1.hasOwnProperty(v)) {
        param2[v] = param1[v];
      }
    });
    return param2;
  },

  //判断是不是数字
  isNumber(val) {
    // isNaN()函数 把空串 空格 以及NUll 按照0来处理 所以先去除，
    if (val === "" || val == null) {
      return false;
    }
    if (!isNaN(val)) {
      //对于空数组和只有一个数值成员的数组或全是数字组成的字符串，isNaN返回false，例如：'123'、[]、[2]、['123'],isNaN返回false,
      //所以如果不需要val包含这些特殊情况，则这个判断改写为if(!isNaN(val) && typeof val === 'number' )
      return true;
    }
    else {
      return false;
    }
  },

  //str:原始字符串，index,开始位置,changeStr，改变后的字
  changeStr(str, index, changeStr) {
    return str.substr(0, index) + changeStr + str.substr(index + changeStr.length);
  },

  //身份证号或者手机号等等字符串想实现替换中间几位字符串
  replacepos(text, start, stop, replacetext) {
    let mystr = text.substr(0, start - 1) + replacetext + text.substr(stop + 1);
    return mystr;
  },

  /*
    功能：验证身份证号码是否有效
    提 示信息：未输入或输入身份证号不正确！
    使用：isIdCard(obj)
    返回：0,1,2,3
    返回0表示身份证号码正确
    返回1表示非法身份证号码
    返回2表示分发地区
    返回3表示非法生日
*/
  isIdCard(obj) {
    var aCity = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙 江", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖 北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西 藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国 外" };
    var iSum = 0;
    var strIDno = obj;
    let sBirthday

    var idCardLength = strIDno.length;
    if (!/^\d{17}(\d|x)$/i.test(strIDno) && !/^\d{15}$/i.test(strIDno))
      return 1; //非法身份证号

    if (aCity[parseInt(strIDno.substr(0, 2))] == null)
      return 2;// 非法地区
    // 15位身份证转换为18位
    if (idCardLength == 15) {
      sBirthday = "19" + strIDno.substr(6, 2) + "-" + Number(strIDno.substr(8, 2)) + "-" + Number(strIDno.substr(10, 2));
      var d = new Date(sBirthday.replace(/-/g, "/"))
      var dd = d.getFullYear().toString() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
      if (sBirthday != dd)
        return 3; //非法生日
      strIDno = strIDno.substring(0, 6) + "19" + strIDno.substring(6, 15);
      strIDno = strIDno + GetVerifyBit(strIDno);
    }

    // 判断是否大于2078年，小于1900年
    var year = strIDno.substring(6, 10);
    if (year < 1900 || year > 2078)
      return 3;//非法生日

    //18位身份证处理
    //在后面的运算中x相当于数字10,所以转换成a
    strIDno = strIDno.replace(/x$/i, "a");
    sBirthday = strIDno.substr(6, 4) + "-" + Number(strIDno.substr(10, 2)) + "-" + Number(strIDno.substr(12, 2));
    var d = new Date(sBirthday.replace(/-/g, "/"))
    if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()))
      return 3; //非法生日
    // 身份证编码规范验证
    for (var i = 17; i >= 0; i--)
      iSum += (Math.pow(2, i) % 11) * parseInt(strIDno.charAt(17 - i), 11);
    if (iSum % 11 != 1)
      return 1;// 非法身份证号

    // 判断是否屏蔽身份证
    var words = new Array();
    words = new Array("11111119111111111", "12121219121212121");

    for (var k = 0; k < words.length; k++) {
      if (strIDno.indexOf(words[k]) != -1) {
        return 1;
      }
    }
    return 0;
  },

  //将个位数补成十位数
  p(s) {
    return s < 10 ? '0' + s : s
  },

  //获取上个月      获取当前 yy - mm - dd
  getPreMonth(date) {
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份  
    var month = arr[1]; //获取当前日期的月份  
    var day = arr[2]; //获取当前日期的日  
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中月的天数  
    var year2 = year;
    var month2 = parseInt(month) - 1;
    if (month2 == 0) {
      year2 = parseInt(year2) - 1;
      month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
      day2 = days2;
    }
    if (month2 < 10) {
      month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
  },

  //获取下个月日期    获取当前 yy - mm - dd
  getNextMonth(date) {
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份  
    var month = arr[1]; //获取当前日期的月份  
    var day = arr[2]; //获取当前日期的日  
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中的月的天数  
    var year2 = year;
    var month2 = parseInt(month) + 1;
    if (month2 == 13) {
      year2 = parseInt(year2) + 1;
      month2 = 1;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
      day2 = days2;
    }
    if (month2 < 10) {
      month2 = '0' + month2;
    }

    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
  },

  //这是比较函数 升序  p是某一属性值,如果有sort，那就是降序     使用：arr.sort(compare('age'))
  compare(p, sort) {
    return function(m, n) {
      var a = m[p];
      var b = n[p];
      if (sort) {
        return b - a; //降序
      } else {
        return a - b; //升序
      }
    }
  },

  // js数组根据对象中的元素去重
  arrayUnique2(arr, name) {
    var hash = {};
    return arr.reduce(function(item, next) {
      hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
      return item;
    }, []);
  },


  //转成Base64
  image2Base64(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL;
  },


  //判断是不是对象
  isObject(obj) {
    return obj instanceof Object;
  },

  // 判断一个对象下是否每个属性都有值
  if_obj_is_null(form) {
    let flag = true;
    for (let key in form) {
      if (this.isArray(form[key]) && !form[key].length) {
        return false
      } else if (!form[key]) {
        return false
      }
    }
    return flag
  },

  //判断是不是 json 数组
  isArray(value) {
    if (Array.isArray(value)) {
      try {
        JSON.parse(JSON.stringify(value));
        return true;
      } catch (error) {
        return false;
      }
    }
    return false;
  },

  //只能输入数字和小数点
  onlyNumber(t) {
    return t.replace(/[^\d^\.]+/g, '')
  },


  //求取两个时间的秒数的差值  yyyy-MM-dd HH:mm:ss
  getSec(time1, time2) {
    var now = new Date();
    var a = time1.split(" ")[0].split("-");
    now.setFullYear(parseInt(a[0]), parseInt(a[1]) - 1, parseInt(a[2]));
    a = time1.split(" ")[1].split(":");
    now.setHours(parseInt(a[0]), parseInt(a[1]), parseInt(a[2]), 0);

    var end = new Date();
    a = time2.split(" ")[0].split("-");
    end.setFullYear(parseInt(a[0]), parseInt(a[1]) - 1, parseInt(a[2]));
    a = time2.split(" ")[1].split(":");
    end.setHours(parseInt(a[0]), parseInt(a[1]), parseInt(a[2]), 0);

    var sec = (end.getTime() - now.getTime()) / 1000;
    return sec;
  },

  // base64转blob
  base64ToBlob(base64) {
    var arr = base64.split(',');
    var mime = arr[0].match(/:(.*?);/)[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    for (var i = 0; i < n; i++) {
      u8arr[i] = bstr.charCodeAt(i);
    }
    var url = URL || webkitURL;
    return url.createObjectURL(new Blob([u8arr], { type: mime }));
  },


  //uniapp  base64转blob二进制文件流
  dataURLtoBlob(dataurl, name) {
    var arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], name, {
      type: mime,
    })
  },

  //获取当前月份的第一天
  getCurrentMonthFirst(day) {
    var date = new Date(day);
    date.setDate(1);
    var month = parseInt(date.getMonth() + 1);
    var day = date.getDate();
    if (month < 10) {
      month = '0' + month
    }
    if (day < 10) {
      day = '0' + day
    }
    return date.getFullYear() + '-' + month + '-' + day;
  },

  //获取当前月份的最后一天
  getCurrentMonthLast(day) {
    var date = new Date(day);
    var currentMonth = date.getMonth();
    var nextMonth = ++currentMonth;
    var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
    var oneDay = 1000 * 60 * 60 * 24;
    var lastTime = new Date(nextMonthFirstDay - oneDay);
    var month = parseInt(lastTime.getMonth() + 1);
    var day = lastTime.getDate();
    if (month < 10) {
      month = '0' + month
    }
    if (day < 10) {
      day = '0' + day
    }
    return date.getFullYear() + '-' + month + '-' + day;
  },

  //判断两个日期之间有多少天时分  	faultDate 开始时间，completeTime结束时间
  dateDifference(faultDate, completeTime) {
    // let d1 = new Date(faultDate);
    // let d2 = new Date(completeTime);
    var stime = new Date(faultDate.replace(/-/g, "/")).getTime();

    var etime = new Date(completeTime.replace(/-/g, "/")).getTime();
    //var etime = Date.parse(new Date());
    var usedTime = etime - stime;  //两个时间戳相差的毫秒数
    var days = Math.floor(usedTime / (24 * 3600 * 1000));
    //计算出小时数
    var leave1 = usedTime % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000));
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000));
    var time
    if (days > 0) {
      time = days + "天" + hours + "时" + minutes + "分";
    } else if (hours > 0) {
      time = `${hours}时${minutes}分`
    } else {
      time = `${minutes}分钟`
    }
    // var time = days;
    return time;
  },

  //取出两个数组的不同元素
  getDiffer(arr1, arr2) {
    return arr1.concat(arr2).filter(function(value, index, arr) {
      return arr.indexOf(value) === arr.lastIndexOf(value);
    });
  },

  //去重
  duplicateRemoval(arr) {
    return [...new Set(arr)]
  },

  toLink(url, type) {
    switch (type) {
      case 'tab':
        uni.switchTab({ url });
        break;
      case 'redirectTo':
        uni.redirectTo({ url });
        break;
      case 'navigateBack'://返回两层页面
        uni.navigateBack({ delta: 1 });
        break;
      case 'reLaunch':
        uni.reLaunch({ url })
        break;
      default:
        uni.navigateTo({ url });
        break;
    }
  },


  back() {
    /*uni.navigateBack({
          delta: 1
        })*/
    //@zxyuns 处理兼容，如果没有上一级界面则返回首页
    const pages = getCurrentPages();
    console.log("pages.length", pages, pages.length)
    if (pages.length === 2) {
      uni.navigateBack({
        delta: 1
      });
    } else if (pages.length === 1) {
      uni.switchTab({
        url: '/pages/tabbar/tabbar-1/tabbar-1',
      })
    } else {
      uni.navigateBack({
        delta: 1
      });
    }
  },


  //根据数组对象中相同属性值组建新数组
  sameSortArr(beforeData, name) {
    let afterData = [];
    let tempArr = [];
    for (let i = 0; i < beforeData.length; i++) {
      if (tempArr.indexOf(beforeData[i][name]) == -1) {
        afterData.push({
          name: beforeData[i][name],
          origin: [beforeData[i]]
        });
        tempArr.push(beforeData[i][name]);
      } else {
        for (let j = 0; j < afterData.length; j++) {
          if (afterData[j].name == beforeData[i][name]) {
            afterData[j].origin.push(beforeData[i]);
            break;
          }
        }
      }
    }
    return afterData
  },


  //时间转时间戳
  getTimeFn(t) {
    if (t) {
      return new Date(t.replace(/-/g, "/")).getTime()
    } else {
      return new Date().getTime()
    }
  },


  //星号处理手机号
  noPassByMobile(str) {
    if (null != str && str != undefined) {
      var pat = /(\d{3})\d*(\d{4})/;
      return str.replace(pat, '$1****$2');
    } else {
      return "";
    }
  },

  //星号处理微信号
  maskWechat(wechat) {
    if (wechat.length <= 3) {
      return wechat.charAt(0) + "*".repeat(wechat.length - 1);
    } else {
      return wechat.slice(0, 3) + "*".repeat(wechat.length - 3);
    }
  },

  //根据数据条数与每页多少条数据计算页数
  pageCount(totalnum, limit) {
    return totalnum > 0 ? ((totalnum < limit) ? 1 : ((totalnum % limit) ? (parseInt(totalnum / limit) + 1) : (totalnum / limit))) : 0;
  },

  //uniapp弹框
  showModal(query) {
    return new Promise(resolve => {
      uni.showModal({
        title: query.title || '提示',
        content: query.content,
        cancelText: query.cancelText || "取消", // 取消按钮的文字  
        confirmText: query.confirmText || "确认", // 确认按钮的文字 
        showCancel: query.hasOwnProperty("showCancel") ? query.showCancel : true, // 是否显示取消按钮，默认为 true
        confirmColor: query.confirmColor || mainColor,
        cancelColor: query.cancelColor || "#000000",
        success: (res) => {
          if (res.confirm) {
            resolve(true)
          } else if (res.cancel) {
            resolve(false)
          }
        },
        fail: e => {
          console.log("为什么没出来", e)
        }
      });
    })
  },

  //uniapp的选项卡
  showActionSheet(query) {
    return new Promise(resolve => {
      uni.showActionSheet({
        itemList: query.itemList,
        // 字体颜色，也可以直接不写这个参数
        itemColor: query.itemColor || "#303133",
        success(res) {
          // 选择其中任意一项后，获取其索引(res.tapIndex)，从0开始
          resolve(res.tapIndex)
        },
        fail(res) {
          // 取消后的操作
        }
      })

    })
  },

  //判断两个json数组，有重复的话，就后面的替代前面的，否则就新增
  filterArr(a, b, key) {
    a = this.deepcopy(a)
    b = this.deepcopy(b)
    let c = []
    if (a.length == 0) {
      a = b
    } else {
      for (let index = 0; index < a.length; index++) {
        let element = a[index];
        for (let j = 0; j < b.length; j++) {
          let item = b[j];
          if (element[key] == item[key]) {  //有重复的就替换
            a[index] = item
          } else {
            c.push(item)
          }
        }
      }
    }
    return this.arrayUnique2(a.concat(c), key);
  },

  //验证字符串是否为手机号
  isPoneAvailable(s) {
    var length = s.length;
    if (length != 11) return false
    if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(s))) {
      return false;  //不满足条件
    } else {
      return true;//满足条件
    }
  },

  //删除url中指定参数值
  delQueryValue(name) {
    var url = window.location.href;
    var urlArr = url.split('?');
    console.log(urlArr)
    if (urlArr.length > 1 && urlArr[1].indexOf(name) > -1) {
      var query = urlArr[1];
      var obj = {}
      var arr = query.split("&");
      for (var i = 0; i < arr.length; i++) {
        arr[i] = arr[i].split("=");
        obj[arr[i][0]] = arr[i][1];
      };
      delete obj[name];
      var urlte = urlArr[0] + '?' + JSON.stringify(obj).replace(/[\"\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
      return urlte;
    } else {
      return url;
    };
  },

  //base64编码
  getEncode64(str) {
    // 对字符串进行编码
    var encode = encodeURI(str);
    // 对编码的字符串转化base64
    var base64 = Base64.btoa(encode);
    return base64;
  },


  //base64解码
  getDecode(str) {
    // 对base64转编码
    var decode = Base64.atob(str);
    // 编码转字符串
    var str = decodeURI(decode)
    return str;
  },

  //js 小数点保留两位，第二位向上进一位
  roundedNum(num) {
    if (!num) num = 0
    return Number.isInteger(num) ? num : Math.ceil(num * 100) / 100;
  },

  // 正则匹配请求地址中的参数函数
  getUrlCode(url, name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ''])[1].replace(/\+/g, '%20')) || null
  },

  //json数组里面的某一个字段是否等于一个变量
  isFieldEqual(arr, field, value) {
    return arr.some(item => item[field] == value);
  },

  //数组里面的某一个字段等于一个变量，则返回数组里面他对应的下标
  findIndexByField(arr, field, value) {
    return arr.findIndex(item => item[field] == value);
  },

  //去掉全部空格
  trimAll(ele) {
    if (typeof ele === "string") {
      return ele.split(/[\t\r\f\n\s]*/g).join("");
    } else {
      console.error(
        `${typeof ele} is not the expected type, but the string type is expected`
      );
    }
  },

  //showToast
  showToast(title, type) {
    let icon
    switch (type) {
      case 0:
        icon = "error"
        break;
      case 1:
        icon = "success"
        break;
      default:
        icon = "none"
        break;
    }
    uni.showToast({ title, icon });
  },

  //判断是不是正确的微信号
  validateWechatNumber(wechat) {
    const regExp = /^[a-zA-Z][-_a-zA-Z0-9]{5,19}$/;
    return regExp.test(wechat);
  },

  //判断两个对象是否相等
  isObjectValueEqual(a, b) {
    //取对象a和b的属性名
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);
    //判断属性名的length是否一致
    if (aProps.length != bProps.length) {
      return false;
    }
    //循环取出属性名，再判断属性值是否一致
    for (var i = 0; i < aProps.length; i++) {
      var propName = aProps[i];
      if (a[propName] !== b[propName]) {
        return false;
      }
    }
    return true;
  },

  //根据生日，算出年龄
  calculateAge(birthday) {
    const birthDate = new Date(birthday);
    const currentDate = new Date();
    let age = currentDate.getFullYear() - birthDate.getFullYear();
    if (currentDate.getMonth() < birthDate.getMonth() ||
      (currentDate.getMonth() === birthDate.getMonth() && currentDate.getDate() < birthDate.getDate())) {
      age--;
    }
    return age;
  },

  //切割的 JSON 数组和每个新数组的大小
  chunkArray(array, chunkSize) {
    const chunks = [];
    for (let i = 0; i < array.length; i += chunkSize) {
      chunks.push(array.slice(i, i + chunkSize));
    }
    return chunks;
  },

  //调用方法获取当前日期3个月之后的日期
  getDateAfterNMonths(data, n) {
    const currentDate = new Date(data);
    currentDate.setMonth(currentDate.getMonth() + n);
    return this.dateTimeFormateFn(currentDate);
  },

  //获取两日期之间日期列表函数   2018-07-25
  getdiffdate(stime, etime) {
    //初始化日期列表，数组
    var diffdate = new Array();
    var i = 0;
    //开始日期小于等于结束日期,并循环
    while (stime <= etime) {
      diffdate[i] = stime;

      //获取开始日期时间戳
      var stime_ts = new Date(stime).getTime();

      //增加一天时间戳后的日期
      var next_date = stime_ts + (24 * 60 * 60 * 1000);

      //拼接年月日，这里的月份会返回（0-11），所以要+1
      var next_dates_y = new Date(next_date).getFullYear() + '-';
      var next_dates_m = (new Date(next_date).getMonth() + 1 < 10) ? '0' + (new Date(next_date).getMonth() + 1) + '-' : (new Date(next_date).getMonth() + 1) + '-';
      var next_dates_d = (new Date(next_date).getDate() < 10) ? '0' + new Date(next_date).getDate() : new Date(next_date).getDate();

      stime = next_dates_y + next_dates_m + next_dates_d;

      //增加数组key
      i++;
    }
    return diffdate
  },

  //字符串超过多少位就显示省略号
  truncateString(str, maxLength) {
    if (!str) return
    if (str.length > maxLength) {
      return str.substring(0, maxLength) + '...';
    } else {
      return str;
    }
  },

  async countAudioTime(src) {
    // #ifndef H5
    const innerAudioContext = uni.createInnerAudioContext();
    innerAudioContext.autoplay = true;
    innerAudioContext.src = src
    return new Promise((resolve, reject) => {
      innerAudioContext.onCanplay(() => {
        let intervalID = setInterval(() => {
          let duration = innerAudioContext.duration
          if (duration != Infinity && duration > 0) {
            clearInterval(intervalID);
            innerAudioContext.destroy()
            resolve(duration)
          }
        }, 1000);
      });
    })
    // #endif

    // #ifdef H5
    const audio = new Audio(src)
    await audio.load();
    while (isNaN(audio.duration) || audio.duration === Infinity) {
      // 延迟一会 不然网页都卡死
      await new Promise(resolve => setTimeout(resolve, 200));
      // 设置随机播放时间，模拟调进度条
      audio.currentTime = 10000000 * Math.random();
    }
    return audio.duration
    // #endif
  },


  //获取字符串的数字部分
  getNumbersFromString(str) {
    const regex = /\d+/g;
    const numbersArray = str.match(regex);
    return numbersArray;
  },

  //判断是不是字符串
  isString(str) {
    return (typeof str == 'string') && str.constructor == String;
  },

  //聊天相关的 im 时间
  im_time_format(imTime) {
    if (!imTime) return
    let differ = this.getdiffdate(this.dateTimeFormateFn(imTime), this.dateTimeFormateFn(new Date()))
    let time = this.dateTimeFormateFn(imTime);
    return `${formatDate(imTime)}`;
    function formatDate(date) {
      date = new Date(date);
      const today = new Date();
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      const beforeYesterday = new Date(today);
      beforeYesterday.setDate(beforeYesterday.getDate() - 2);

      const dayOfWeek = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];

      if (date.toDateString() === today.toDateString()) {
        return "今天"; //今天
      } else if (date.toDateString() === yesterday.toDateString()) {
        return "昨天";
      } else if (date.toDateString() === beforeYesterday.toDateString()) {
        return "前天";
      } else if (differ.length < 6) {
        return dayOfWeek[date.getDay()];
      } else {
        return time
      }
    }
  },
}